package cglib动态代理;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author ：Xiaochen
 * @date ：Created in 2022/11/9 22:28
 * @description：
 * @modified By：
 * @version:
 */
public class ProxyFactory implements MethodInterceptor {
    //被代理的对象
    private Object target;

    public ProxyFactory(Object target) {
        this.target = target;
    }
    //获取代理对象
    public Object getInstance(){
        //创建一个工具---生成代理对象
        Enhancer enhancer = new Enhancer();
        //指定被代理的父类
        enhancer.setSuperclass(target.getClass());
        //代理的回调方法
        enhancer.setCallback(this);
        return enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        intro();
        watch();
        //调用被代理对象的方法
        Object result = method.invoke(target, objects);

        return result;
    }
    public void watch(){
        System.out.println("看房");
    }
    public void intro(){
        System.out.println("房源介绍");
    }
}